package com.study.happystudy.controller;


import com.study.happystudy.entity.ResultEntity;
import com.study.happystudy.po.FriendshipList;
import com.study.happystudy.po.Rank;
import com.study.happystudy.po.User;
import com.study.happystudy.service.impl.ExamPaperServiceImpl;
import com.study.happystudy.service.impl.FriendshipServiceImpl;
import com.study.happystudy.service.impl.PointTransactionServiceImpl;
import com.study.happystudy.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 用户
 *
 * @author wfs
 * @version 1.0
 * @since 2023/05/04
 */

@CrossOrigin//跨域
@RestController//遵循RestFul
@RequestMapping("user/")//请求路径
public class UserController {
    @Resource
    UserServiceImpl userService;

    @Resource
    FriendshipServiceImpl friendshipService;

    @Resource
    PointTransactionServiceImpl pointTransactionService;

    /**
     * 登录
     *
     * @param phone    手机号
     * @param password 密码
     * @return JSON
     */
//    127.0.0.0:8080/user/Login?phone=123&password=123
    @GetMapping("Login")
    public String Login(@RequestParam("phone") String phone, @RequestParam("password") String password) {
        User user = userService.Login(phone, password);
        if (user != null) {
            return ResultEntity.Success(1, user);
        } else {
            return ResultEntity.Fail(-1, "登录失败");
        }
    }

    /**
     * 修改密码
     *
     * @param phone    手机号
     * @param password 密码
     * @return JSON
     */
    @PostMapping("upUserPwd")
    public String upUserPwd(@RequestParam("phone") String phone, @RequestParam("password") String password) {
        int res = userService.upUserPwd(phone, password);
        if (res > 0) {
            return ResultEntity.Success(1, "哟西");
        } else {
            return ResultEntity.Fail(-1, "修改失败");
        }
    }

    /**
     * 注册
     *
     * @param type        用户类型
     * @param name        姓名
     * @param phone       手机号
     * @param password    密码
     * @param institution 机构/学校
     * @return JSON
     */
    @PostMapping("register")
    public String register(@RequestParam("type") String type, @RequestParam("name") String name,
                           @RequestParam("phone") String phone, @RequestParam("password") String password,
                           @RequestParam("institution") String institution, @RequestParam("gender") char gender) {
        int res = userService.register(type, name, phone, password, institution, gender);
        if (res > 0) {
            return ResultEntity.Success(1, "哟西");
        } else {
            return ResultEntity.Fail(-1, "注册失败");
        }
    }

    /**
     * 获取好友列表
     *
     * @param uid    用户id
     * @param status 当前状态
     * @return JSON
     */
    @GetMapping("getFriendList")
    public String getFriendshipsByUserId(@RequestParam("uid") int uid,
                                         @RequestParam("status") String status) {
        List<FriendshipList> list = friendshipService.getFriendshipsByUserId(uid, status);
        if (list != null) {
            return ResultEntity.Success(list.size(), list);
        } else {
            return ResultEntity.Fail(-1, "获取失败");
        }
    }

    /**
     * 获取好友请求列表
     *
     * @param uid 用户id
     * @return JSON
     */
    @GetMapping("getFriendshipAskList")
    public String getFriendshipAskList(@RequestParam("uid") int uid) {
        List<FriendshipList> list = friendshipService.getFriendshipAskList(uid);
        if (list != null) {
            return ResultEntity.Success(list.size(), list);
        } else {
            return ResultEntity.Fail(-1, "获取失败");
        }
    }

    /**
     * 添加好友关系
     *
     * @param uid 用户id
     * @param fid 添加用户id
     * @return JSON
     */
    @PostMapping("addFriendship")
    public String addFriendship(@RequestParam("uid") int uid,
                                @RequestParam("fid") int fid) {
        int res = friendshipService.addFriendship(uid, fid);
        if (res > 0) {
            return ResultEntity.Success(1, "哟西");
        } else {
            return ResultEntity.Fail(-1, "添加失败");
        }
    }

    /**
     * 更新好友关系状态
     *
     * @param friendshipId 关系id
     * @param status       状态
     * @return JSON
     */
    @PostMapping("updateFriendshipStatus")
    public String updateFriendshipStatus(@RequestParam("friendshipId") int friendshipId,
                                         @RequestParam("status") String status) {
        int res = friendshipService.updateFriendshipStatus(friendshipId, status);
        if (res > 0) {
            return ResultEntity.Success(1, "哟西");
        } else {
            return ResultEntity.Fail(-1, "更新失败");
        }
    }

    /**
     * 根据id查找用户
     *
     * @param id 用户id
     * @return JSON
     */
    @GetMapping("findUserById")
    public User findUserById(Integer id) {
        return userService.findUserById(id);
    }

    @PostMapping("updatePoints")
    public String updatePoints(Integer id, Integer points) {
        User user = userService.findUserById(id);
        if (user == null) return ResultEntity.Fail(-1, "更新失败了捏~");
        if (!"学生".equals(user.getUsertype())) return ResultEntity.Fail(-1, "只有小孩可以有积分哦~");
        userService.updatePoints(id, points);
        return ResultEntity.Success(1, "哟西");
    }

    @PostMapping("increasePoints")
    public String increasePoints(Integer uid, Integer points, String reason) {
        User user = userService.findUserById(uid);
        if (user == null) return ResultEntity.Fail(-1, "更新失败了捏~");
        if (!"学生".equals(user.getUsertype())) return ResultEntity.Fail(-1, "只有小孩可以有积分哦~");

        userService.updatePoints(uid, user.getStudentPoints() + points);

        pointTransactionService.insertPointTransaction(uid, points, reason);

        return ResultEntity.Success(1, "哟西");
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     * @return JSON
     */
    @PostMapping("deleteUser")
    public String deleteUser(@RequestParam("user_id") Integer id) {
        boolean res = userService.deleteUser(id);

        if (res) return ResultEntity.Success(1, "哟西");


        return ResultEntity.Fail(-1, "未找到该用户");
    }

    /**
     * 根据搜索词查找用户
     *
     * @param searchTerm 搜索词
     * @return JSON
     */
    @GetMapping("findUserBySearchTerm")
    public List<User> findUserBySearchTerm(String searchTerm) {
        return userService.findUserBySearchTerm(searchTerm);
    }

    /**
     * 更新用户信息
     *
     * @param nickname     昵称
     * @param headPortrait 头像
     * @param introduction 简介
     * @param age          年龄
     * @param institution  机构
     * @param gender       性别
     * @param id           用户id
     * @return JSON
     */
    @PostMapping("updateUser")
    String updateUser(String nickname, String headPortrait, String introduction, int age, String institution, String gender, int id) {
        User u = userService.findUserById(id);
        if (u == null) return ResultEntity.Fail(-1, "该用户不存在");
        if (age == -1) {
            age = u.getUserAge();
        }
        if (nickname == "") {
            nickname = u.getUserNickname();
        }
        if (headPortrait == "") {
            headPortrait = u.getUserHeadPortrait();
        }
        if (introduction == "") {
            introduction = u.getUserIntroduction();
        }
        if (institution == "") {
            institution = u.getInstitution();
        }
        if (gender == "") {
            gender = String.valueOf(u.getGender());
        }
        userService.updateUser(nickname, headPortrait, introduction, age, institution, gender.charAt(0), id);
        return ResultEntity.Success(1, "更新成功");
    }

    @GetMapping("getPointTransactionByUserId")
    public Object getPointTransactionByUserId(@RequestParam int userId) {

        if (userService.findUserById(userId) == null) {
            return ResultEntity.Fail(-1, "用户不存在");
        }

        return pointTransactionService.getPointTransactionByUserId(userId);
    }

    @GetMapping("getFriendRank")
    public Object getFriendRank(@RequestParam Integer uid) {
        User user = userService.findUserById(uid);

        if (user == null) {
            return ResultEntity.Fail(-1, "用户不存在");
        }

        List<Rank> r = userService.getFriendRank(uid);

        r.add(user.toRank());

        r.sort(Comparator.comparingInt(Rank::getStudentPoints).reversed());
        for (int i = 0; i < r.size(); i++) {
            if (!Objects.equals(r.get(i).getUserType(), "学生")) {
                //不是学生就删除
                r.remove(i);
                i--;
            }
        }

        return r;
    }

        @GetMapping("getAllRank")
    public Object getAllRank() {
        try {
            return userService.getAllRank();
        } catch (Exception e) {
            return ResultEntity.Fail(-1, "获取排行榜失败");
        }
    }
}
